package com.ucode.admin.cgms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ArrayUtil;
import com.ucode.admin.base.core.CurrentLoginUserService;
import com.ucode.cgms.service.CgmsCommissionFlowService;
import com.ucode.model.cgms.CgmsCommissionFlow;
import com.ucode.model.cgms.convert.CgmsCommissionFlowConvert;
import com.ucode.model.cgms.enums.CgmsCommissionStatusEnum;
import com.ucode.model.cgms.enums.CgmsCommissionTypeEnum;
import com.ucode.model.cgms.form.CgmsCommissionFlowForm;
import com.ucode.model.cgms.vo.CgmsCommissionFlowVO;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.util.IdentifyUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 佣金流水后台管理接口
 * @Author: Claude
 * @Date: 2023/05/26 14:20
 * @Version: 1.0
 */
@Tag(name = "管理后台 - 陪玩社区系统 - 佣金流水")
@RestController
@RequestMapping("/cgms/commission-flow")
@Validated
public class CgmsCommissionFlowController {

    @Resource
    private CgmsCommissionFlowService cgmsCommissionFlowService;
    
    @Resource
    private CurrentLoginUserService currentLoginUserService;

    @GetMapping("/page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('cgms:commission-flow:query')")
    public ResponseResult<Paginator<CgmsCommissionFlowVO>> pageList(
            @Schema(description = "用户ID") @RequestParam(value = "userId", required = false) Long userId,
            @Schema(description = "订单ID") @RequestParam(value = "orderId", required = false) Long orderId,
            @Schema(description = "订单编号") @RequestParam(value = "orderNo", required = false) String orderNo,
            @Schema(description = "佣金类型") @RequestParam(value = "commissionType", required = false) Integer commissionType,
            @Schema(description = "状态") @RequestParam(value = "statuz", required = false) Integer statuz,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]") 
            @RequestParam(value = "createTimeInterval", required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码", example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数", example="10") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        
        Map<String,Object> condition = new HashMap<>();
        condition.put("userId", userId);
        condition.put("orderId", orderId);
        if(StrUtil.isNotBlank(orderNo))
            condition.put("orderNo", StrUtil.concat(true,"%", orderNo,"%"));
        condition.put("commissionType", commissionType);
        condition.put("statuz", statuz);
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime", createTimeInterval[0]);
            condition.put("endTime", createTimeInterval[1]);
        }
        
        condition.put("deltag", false);
        
        Paginator<CgmsCommissionFlow> paginator = cgmsCommissionFlowService.queryPageForList(condition, pageSize, pageNum);
        Paginator<CgmsCommissionFlowVO> voPage = CgmsCommissionFlowConvert.INSTANCE.convertPage(paginator);
        
        // 设置枚举名称
        if (CollUtil.isNotEmpty(voPage.getList())) {
            voPage.getList().forEach(vo -> {
                vo.setCommissionTypeName(vo.getCommissionType() != null ? 
                        CgmsCommissionTypeEnum.getNameByCode(vo.getCommissionType()) : null);
                vo.setStatuzName(vo.getStatuz() != null ? 
                        CgmsCommissionStatusEnum.getNameByCode(vo.getStatuz()) : null);
            });
        }
        
        return ResponseResult.success(voPage);
    }

    @GetMapping("/get/{id}")
    @Parameter(description="主键ID", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "主键获得信息")
    @PreAuthorize("@usfs.hasPermission('cgms:commission-flow:query')")
    public ResponseResult<CgmsCommissionFlowVO> getById(@PathVariable(name="id", required=true) Long id) {
        CgmsCommissionFlow bean = cgmsCommissionFlowService.validate(id);
        CgmsCommissionFlowVO vo = CgmsCommissionFlowConvert.INSTANCE.convert(bean);
        vo.setCommissionTypeName(bean.getCommissionType() != null ? 
                CgmsCommissionTypeEnum.getNameByCode(bean.getCommissionType()) : null);
        vo.setStatuzName(bean.getStatuz() != null ? 
                CgmsCommissionStatusEnum.getNameByCode(bean.getStatuz()) : null);
        return ResponseResult.success(vo);
    }

    @PostMapping("/create")
    @Operation(summary = "创建")
    @PreAuthorize("@usfs.hasPermission('cgms:commission-flow:create')")
    public ResponseResult<Long> create(@Valid @RequestBody CgmsCommissionFlowForm form) {
        CgmsCommissionFlow bean = CgmsCommissionFlowConvert.INSTANCE.convert(form);
        bean.setId(IdentifyUtils.getDefaultSnowflakeId());
        bean.setStatuz(CgmsCommissionStatusEnum.PENDING.getCode());
        bean.setDeltag(false);
        cgmsCommissionFlowService.insert(bean);
        return ResponseResult.success(bean.getId());
    }

    @PostMapping("/update/{id}")
    @Parameter(description="主键ID", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "修改")
    @PreAuthorize("@usfs.hasPermission('cgms:commission-flow:update')")
    public ResponseResult<Object> update(@PathVariable(name="id", required=true) Long id,
                                        @Valid @RequestBody CgmsCommissionFlowForm form) {
        CgmsCommissionFlow bean = cgmsCommissionFlowService.validate(id);
        CgmsCommissionFlowConvert.INSTANCE.update(form, bean);
        cgmsCommissionFlowService.update(bean);
        return ResponseResult.success();
    }

    @PostMapping("/delete/{id}")
    @Parameter(description="主键ID", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "物理删除")
    @PreAuthorize("@usfs.hasPermission('cgms:commission-flow:delete')")
    public ResponseResult<Object> delete(@PathVariable(name="id", required=true) Long id) {
        cgmsCommissionFlowService.deleteByPrimaryKey(id);
        return ResponseResult.success();
    }
    
    @PostMapping("/logic-delete/{id}")
    @Parameter(description="主键ID", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "逻辑删除")
    @PreAuthorize("@usfs.hasPermission('cgms:commission-flow:logic-delete')")
    public ResponseResult<Object> logicDelete(@PathVariable(name="id", required=true) Long id) {
        cgmsCommissionFlowService.logicDeletePrimaryKey(id);
        return ResponseResult.success();
    }
    
    @PostMapping("/batch-logic-delete")
    @Operation(summary = "批量逻辑删除")
    @PreAuthorize("@usfs.hasPermission('cgms:commission-flow:logic-delete')")
    public ResponseResult<Object> batchLogicDelete(@NotEmpty(message = "编号集合为空") 
                                                 @Size(min = 1, max = 20, message = "编号集合数量为1-20条")
                                                 @RequestParam(value = "ids", required = true) List<Long> ids) {
        cgmsCommissionFlowService.logicDeleteByPrimaryKeys(ids);
        return ResponseResult.success();
    }
    
    @PostMapping("/update-status")
    @Operation(summary = "修改状态")
    @PreAuthorize("@usfs.hasPermission('cgms:commission-flow:update')")
    public ResponseResult<Boolean> updateStatus(@Schema(description = "编号集合", requiredMode = Schema.RequiredMode.REQUIRED)
                                               @NotEmpty(message = "编号集合为空")
                                               @Size(min = 1, max = 20, message = "编号集合数量为1-20条")
                                               @RequestParam(value = "ids", required = true) List<Long> ids,
                                               @Schema(description = "状态", requiredMode = Schema.RequiredMode.REQUIRED,
                                                      allowableValues = {"0", "1", "2"})
                                               @RequestParam(value = "status", required = true) Integer status) {
        return ResponseResult.success(cgmsCommissionFlowService.updateStatus(ids, status) > 0);
    }
    
    @PostMapping("/batch-settle")
    @Operation(summary = "批量结算佣金")
    @PreAuthorize("@usfs.hasPermission('cgms:commission-flow:settle')")
    public ResponseResult<Boolean> batchSettle(@Schema(description = "编号集合", requiredMode = Schema.RequiredMode.REQUIRED)
                                             @NotEmpty(message = "编号集合为空")
                                             @Size(min = 1, max = 20, message = "编号集合数量为1-20条")
                                             @RequestParam(value = "ids", required = true) List<Long> ids) {
        return ResponseResult.success(cgmsCommissionFlowService.batchSettle(ids) > 0);
    }
    
    @PostMapping("/batch-cancel")
    @Operation(summary = "批量取消佣金")
    @PreAuthorize("@usfs.hasPermission('cgms:commission-flow:cancel')")
    public ResponseResult<Boolean> batchCancel(@Schema(description = "编号集合", requiredMode = Schema.RequiredMode.REQUIRED)
                                             @NotEmpty(message = "编号集合为空")
                                             @Size(min = 1, max = 20, message = "编号集合数量为1-20条")
                                             @RequestParam(value = "ids", required = true) List<Long> ids) {
        return ResponseResult.success(cgmsCommissionFlowService.batchCancel(ids) > 0);
    }
    
    @GetMapping("/getByOrderId/{orderId}")
    @Parameter(description="订单ID", name = "orderId", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "根据订单ID获取佣金流水")
    @PreAuthorize("@usfs.hasPermission('cgms:commission-flow:query')")
    public ResponseResult<List<CgmsCommissionFlowVO>> getByOrderId(@PathVariable(name="orderId", required=true) Long orderId) {
        List<CgmsCommissionFlow> list = cgmsCommissionFlowService.getCommissionFlowByOrderId(orderId);
        List<CgmsCommissionFlowVO> voList = CgmsCommissionFlowConvert.INSTANCE.convertList(list);
        
        // 设置枚举名称
        if (CollUtil.isNotEmpty(voList)) {
            voList.forEach(vo -> {
                vo.setCommissionTypeName(vo.getCommissionType() != null ? 
                        CgmsCommissionTypeEnum.getNameByCode(vo.getCommissionType()) : null);
                vo.setStatuzName(vo.getStatuz() != null ? 
                        CgmsCommissionStatusEnum.getNameByCode(vo.getStatuz()) : null);
            });
        }
        
        return ResponseResult.success(voList);
    }
} 